const temp = lrc.split('\n')
function StrToObj () {
  const words = temp.map(item => item.split(']')[1])
  const t = TimeToNum()
  let lrcArr = []
  for (let i = 0; i < temp.length; i++){
    const obj = {
      time: t[i],
      word: words[i]
    }
    lrcArr.push(obj)
  }
  return lrcArr
}

const lrcArr = StrToObj()

function TimeToNum() {
  let time = temp.map(item => item.split(']')[0])
  time = time.map(item => item.replace('[',''))  // 也可用time.substring(1)
  for (let i = 0; i < time.length; i++) {
    const minute = time[i].split(':')[0]
    const second = time[i].split(':')[1]
    time[i] = (+minute * 60 + +second).toFixed(2)
  }
  return time
}

const doms = {
  audio: document.querySelector('audio'),
  ul: document.querySelector('.container ul'),
  container: document.querySelector('.container')
}

function findIndex() {
  const cur = doms.audio.currentTime  //currentTime:进度条
  for (let i = 0; i < lrcArr.length; i++) {
    if (cur < lrcArr[i].time) {      //lrcArr
      return i - 1
    }
  }
  return lrcArr.length - 1
}

function createLi () {
  const frag = document.createDocumentFragment()
  for (let i = 0; i < lrcArr.length; i++) {
    const li = document.createElement('li')
    li.textContent = lrcArr[i].word      // lrcArr
    frag.appendChild(li)
    /**
     * 文档注释  
     * doms.ul.appendChild(li) //多次改动dom树效率太低，可改用文档片段document.createDocumentFragment()
    */
    }
  doms.ul.appendChild(frag)
}

createLi()//调用
const containerHeight = doms.container.clientHeight //容器高度
const liHeight = doms.ul.children[0].clientHeight  //歌词高度
const maxMoving = doms.ul.clientHeight - containerHeight // 歌词移动的最远距离=ul当前高度-容器高度

function setMoving () {
  const index = findIndex()
  let moving = ( index + 0.5 ) * liHeight - containerHeight / 2
  if (moving < 0) moving = 0
  if (moving > maxMoving) moving = maxMoving
  doms.ul.style.transform = `translateY(-${moving}px)`// 注意是ul移动,以及反引号的用法
  // 高亮
  const active = doms.ul.querySelector('.active') // 注意是ul不是document
  if (active) active.classList.remove('active')
  const li = doms.ul.children[index]
  if (li) li.classList.add('active')
}

doms.audio.addEventListener('timeupdate', setMoving)//时间更新时间：用于进度条